define(
  ["require", "jquery", "jsrender", "jqueryui", "bip.cache", "datatables"],
  function(require) {

    var $ = require("jquery");
    var $cache = require("bip.cache");

    (function extendJquery($){
       $.ajaxSettings.accepts.json += ", text/x-json";

    })($);  // end of function extendJquery()

    (function customizeDatatables(DataTable){
       $.extend(DataTable.defaults,
         { "iDisplayLength": 1000,
           "aLengthMenu": [[10, 25, 50, 100, 1000, 5000, -1], [10, 25, 50, 100, 1000, 5000, "所有（不分页）"]]
         }
       );

    })($.fn.DataTable);
    
    (function fixDialogFocus(dialog){
        $.extend(dialog.prototype,
          {u : "dialog"
          }
        );        
     })($.ui.dialog);
    
    function Logger(len){
    	this._logLength = len;
    	this._logs = new Array();
    	this._logCount = 0;
    }
    
    Logger.prototype.log = function(){
    	if(arguments.length === 0){
    		console.log("log text is null");
    		return;
    	}
    	
    	var currentIndex = this._logCount % this._logLength;
    	var logMsg = obtainLogString(arguments);
    	this._logs[currentIndex] = logMsg;
    	console.log("biplog: ", logMsg);
    	this._logCount += 1;

    	if ($("#bip-show-logs-dialog").length) {
    	   var $txtArea = $("#bip-show-logs-dialog > textarea").first();
    	   var logLines = $txtArea.html();
    	   $txtArea.html(logLines + "\n" + logMsg);
    	   var txtArea = $txtArea[0];
    	   txtArea.scrollTop = txtArea.scrollHeight;
    	}

    }
    
    Logger.prototype.getLogs = function(){
    	var tmpLog = "";

    	var currentIndex = this._logCount % this._logLength;
    	if(this._logCount >= this._logLength){
    	    tmpLog = this._logs.slice(currentIndex, this._logLength).join("\n") + "\n";
    	}
		tmpLog += this._logs.slice(0, currentIndex).join("\n");
		return tmpLog;
    }

    Logger.prototype.showLogs = function(){
    	if ($("#bip-show-logs-dialog").length){
    	   return;
    	}
        var logs = this.getLogs.apply(this, arguments);
        
        var options = {
        		"width" : 800, 
        		"height" : 500,
        		"position" : {
        			my:"right-5 top",
        			at:"right top",
        			of:$("body")
        		}
        };
        
    	openMessageDialog(logs, "程序日志", false, "bip-show-logs-dialog", options);
    }

    function obtainLogString(args){
    	var tmpLog = (new Date()).toLocaleString() + " ";
    	for(var i=0; i<args.length; i++){
    		tmpLog += args[i];
    	}
    	return tmpLog;
    }
    
    function openMessageDialog(message,title,modal,divID, options){
    	if(divID === undefined){
    		divID = "bip-message-dialog";
    	}
    	
    	$("body").append("<div id=\"" + divID + "\" title=\"" + (title ? title : "提示对话框") + "\"></div>");
    	
    	var width = (options.width === undefined ? 400 : options.width);
    	var height = (options.height === undefined ? 300 : options.height);
    	
    	var textWidthPercent = (width >= 500 ? 98 : 96);
    	var textHeightPercent = (height >= 400 ? 92 : 85);
    	
    	$("#" + divID).empty().append("<textarea name=\"mytextarea\" style=\"width:" + textWidthPercent + "%; height:" + textHeightPercent + "%;\" readonly>" + message + "</textarea>");
    	return $("#" + divID).dialog({
				    		close:function(){
				    			$(this).dialog("destroy");
				    			$("#" + divID).remove();
				    		},
				    		autoOpen: true,
				    		position:(options.position === undefined ? {} : options.position),
				    		modal:(modal ? true : false),
				    		width: width,
				            height: height,
				    		buttons: {
				    			'确定': function() {
				    				$(this).dialog("close");
				    			}
				    		}
				    	});
    }
    
    function showOneMessage(){
    	if(arguments.length === 0){
    		console.log("message text is null");
    		return;
    	}
    	
    	var tmpMsg = "";
    	var title = "";
    	var options = {};
    	var messageLength = 0;
    	if(arguments.length >= 2){
    		title = arguments[0];
    		//添加message的options，默认支持width,height
    		if($.isPlainObject(arguments[arguments.length - 1])){
    			messageLength = arguments.length - 1;
    			options = arguments[arguments.length - 1];
    		}else{
    			messageLength = arguments.length;
    		}
    		
    		for ( var i = 1; i < messageLength; i++) {
    			tmpMsg += arguments[i];
    			if(i < arguments.length - 1){
    				tmpMsg += "\n";
    			}
    		}
    	}else{
    		title = "消息提示对话框";
    		tmpMsg = arguments[0];
    	}
    	
    	openMessageDialog(tmpMsg, title, true, "bip-show-message-dialog", options);
    }
    
    function openconfirmDialog(callback,message,title,argsData,modal){
    	$("body").append("<div id=\"bip-confirm-dialog\" title=\"" + (title ? title : "确认对话框") + "\"></div>");
    	$("#bip-confirm-dialog").empty().append("<textarea name=\"mytextarea\" style=\"width:95%;height:240px;\">" + message + "</textarea>");
    	return $('#bip-confirm-dialog').dialog({
				    		close:function(){
				    			$(this).dialog("destroy");
				    			$("#bip-confirm-dialog").remove();
				    		},
				    		autoOpen: true,
				    		position:{
				    			my:"center top",
				    			at:"center top",
				    			of:$("body")
				    		},
				    		modal:(modal ? true : false),
				    		width: 400,
				            height: 400,
				    		buttons: {
				    			'确定': function() {
				    				$(this).dialog("close");
				    				callback.call(null, argsData);
				    			},
				    			'取消':function(){
				    				$(this).dialog("close");
				    			}
				    		}
				    	});
    }
    
    function showConfirmDialog(){
    	if(arguments.length <= 0 || arguments.length > 4){
    		console.log("callback is null,open confirm dialog fail.");
    		return;
    	}
    	
    	var callback = arguments[0];
    	var title = "确认对话框";
    	var message = "请确定！";
    	var argsData = null;
    	if(arguments.length === 2){
    		message = arguments[1];
    	}else if(arguments.length === 3){
    		message = arguments[1];
    		title = arguments[2];
    	}else{
    		message = arguments[1];
    		title = arguments[2];
    		argsData = arguments[3];
    	}
    	openconfirmDialog(callback, message, title, argsData, true);
    }

    var patternScriptBegin = /<script/;
    var patternScriptEnd = /<\/script\s*>/;
    var patternEvents = /\son\w+\s*=/;

    patternScriptBegin.ignoreCase = true;
    patternScriptBegin.multiline = true;
    patternScriptEnd.ignoreCase = true;
    patternScriptEnd.multiline = true;
    patternEvents.ignoreCase = true;
    patternEvents.multiline = true;

    function noscript(s){
      if (!s){
        return s;
      }
      s = s.replace(patternScriptBegin, "<br />警告：显示内容中存在脚本代码(script)，可能是攻击行为或安全缺陷<br /><pre>&lt;script");
      s = s.replace(patternScriptEnd, "&lt;/script&gt;</pre><br />");
      if (patternEvents.test(s)){
         s = s.replace(patternEvents, "blockevent=");
         s += "<br />警告：显示内容中存在事件脚本代码(onXXX='...')，可能是攻击行为或安全缺陷<br />";
      }
      return s;
    }

    $.views.converters("noscript", noscript);

    var _logger = new Logger(5000);

    var $bip = {
      log : function(){ _logger.log.apply(_logger, arguments); },
      showLog : function(){ _logger.showLogs.apply(_logger, arguments); },
      showMsg : showOneMessage,
      showConfirm: showConfirmDialog,
      clearAllCache : function() { $cache.clearAll(); },
      noscript : noscript,
    };

    return $bip;
  }
);

